package com.wyg.epdata.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wyg.epdata.common.constant.BaseConstant;
import com.wyg.epdata.entity.respones.EntityValidResp;
import com.wyg.epdata.entity.respones.WordsResp;
import com.wyg.epcommonbase.common.util.file.StreamUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: WangYongGan
 * @Date: 2021/11/1 16:31
 * @Description:
 */
@Slf4j
public class HttpUtil {
    static boolean sendEmail = BaseConstant.os.equals("linux");

    public static List<String> sendPostGetEntities(JSONObject jsonObject) throws IOException {
        String result = send(BaseConstant.urlNer, jsonObject.toString(), "utf-8");
        return getEneity(result);
    }

    @SneakyThrows
    public static boolean setPostEmotionOfEntity(JSONObject jsonObject) {
        ;
        String result = send(BaseConstant.urlEnontion, jsonObject.toString(), "utf-8");
        if (!(result.contains("1.0") || result.contains("0.0")))
            log.error("resultError: " + result);
        return result.contains("1.0");
    }

    @SneakyThrows
    public static Object sendGet(String url, Map<String, String> params) {
        CloseableHttpClient client = HttpClients.createDefault();
        url += "?";
        StringBuilder urlBuilder = new StringBuilder(url);
//        for (String k : params.keySet()) {
//            urlBuilder.append(k);
//            urlBuilder.append("=");
//            urlBuilder.append(params.get(k));
//        }
        HttpGet httpGet = new HttpGet(urlBuilder.toString());
        CloseableHttpResponse response = client.execute(httpGet);
        InputStream content = response.getEntity().getContent();
        WordsResp resp = JSON.parseObject(StreamUtil.streamToString(content), WordsResp.class);
        response.close();
        return resp;
    }

    @SneakyThrows
    public static String send(String url, String jsonObject, String encoding) {
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        //装填参数
        StringEntity postBody = new StringEntity("[" + jsonObject.toString() + "]", "UTF-8");
        postBody.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json;charset=utf-8"));
        //设置参数到请求对象中
        httpPost.setEntity(postBody);
//        System.out.println("请求参数："+nvps.toString());
        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
//        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Content-type", "application/json;charset=utf-8");
        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = null;
        boolean flag = true;
        while (flag) {
            try {
                response = client.execute(httpPost);
                flag = false;
            } catch (IOException e) {
                System.out.println("请求API出错:" + url);
                if (sendEmail) {
//                    EmailUtil.sendEmail("2245316014@qq.com","2224569342@qq.com","金融舆情-数据处理错误","请求API出错:"+url);
                    sendEmail = false;
                }
                flag = true;
            }
        }
        //获取结果实体
        HttpEntity entity = response.getEntity();
        //按指定编码转换结果实体为String类型
        String body = entity == null ? "" : EntityUtils.toString(entity, encoding);
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }

    public static String unicodeDecode(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }

    public static int getResultNum(String result) {
        //result:[1.0]/[0.0]
        result = result.replace("[", "");
        result = result.replace("]", "");
        result = result.replace(" ", "");
        result = result.replace("\n", "");
        Integer i = new Integer(Integer.parseInt("" + result.charAt(0)));
        System.out.println(i);
        return i;

    }

    public static ArrayList<String> getEneity(String result) {
        result = unicodeDecode(result);
        result = result.replace("\n", "");
        result = result.replace(" ", "");
        result = result.replace("[", "");
        result = result.replace("]", "");
        result = result.replace("\"", "");

        String[] split = result.split(",");
        TreeSet<String> list = new TreeSet<String>();
        for (String s : split) {
            list.add(s);
        }
        ArrayList<String> l = new ArrayList<String>();
        for (String s : list) {
            if (s.equals("") || s.equals(" "))
                continue;
            l.add(s);
        }
        return l;
    }

    @SneakyThrows
    public static EntityValidResp entityIsValid(String name) {
        CloseableHttpClient client = HttpClients.createDefault();
        String url = BaseConstant.urlEntityIsValid;
        url += "/" + name;
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = client.execute(httpGet);
        InputStream responseStream = response.getEntity().getContent();
        EntityValidResp entityTest = JSON.parseObject(StreamUtil.streamToString(responseStream), EntityValidResp.class);
        response.close();
        return entityTest;
    }

}
